import React, {Component} from "react";
import './index.css';

const MyContext = React.createContext("");
const {Provider, Consumer} = MyContext;

export default class A extends Component {
	state = {username: 'tom'}
	render() {
		const {username} = this.state;
		let userInfo = {
			username: username,
			age: 18
		}
		return (
			<div className="parent">
				<h3>我是A组件</h3>
				<h4>我的用户名是: {username}</h4>
				<Provider value={userInfo}>
					<B />
				</Provider>
			</div>
		)
	}
}

class B extends Component {
	render() {
		// console.log(this.context);
		return (
			<div className="child">
				<h3>我是B组件</h3>
				<h4>我从A组件接收到的用户名: ??</h4>
				<C />
			</div>
		)
	}
}

// class C extends Component {
// 	// 申明接收，必须叫 contextType
// 	static contextType = MyContext;
// 	render() {
// 		console.log(this.context);
// 		const {username, age} = this.context;
// 		return (
// 			<div className="grand">
// 				<h3>我是C组件</h3>
// 				<h4>我从A组件接收到的用户名: {username}, 年龄是: {age}</h4>
// 			</div>
// 		)
// 	}
// }

const C = () => {
	return (
		<div className="grand">
			<h3>我是C组件</h3>
			<h4>我从A组件接收到的用户名: , 年龄是:
				<Consumer>
					{
						value => {
							return `${value.username}, 年龄是: ${value.age}`
						}
					}
				</Consumer>
			</h4>
		</div>
	)
}